<!--
 * @author  dumeng
-->
<template>
  <div class="common-export">
    <el-button
      v-loading.fullscreen.lock="fullscreenLoading"
      class="filter-item"
      style="margin-left: 10px;"
      @click="queryTableHeaders"
    >导出</el-button>
    <el-dialog
      v-el-drag-dialog
      :close-on-click-modal="false"
      title="选择表头信息"
      :visible.sync="selectTableHeader"
      center
      width="500px"
    >
      <el-checkbox
        v-model="checkAll"
        :indeterminate="isIndeterminate"
        @change="handleCheckAllChange"
      >全选</el-checkbox>
      <el-checkbox-group
        v-model="checkedList"
        class="can-check-all"
        style="margin-top:15px;"
        @change="handleCheckedChange"
      >
        <el-tooltip class="item" effect="dark" content="鼠标点击标题拖动可以调整显示顺序" placement="left">
          <draggable :list="tableHeaders" :animation="340" group="row" @end="onEnd">
            <el-checkbox
              v-for="(item,index) in tableHeaders"
              :key="index"
              :label="item.prop"
            >{{ item.label }}</el-checkbox>
          </draggable>
        </el-tooltip>
      </el-checkbox-group>
      <div slot="footer" class="dialog-footer">
        <el-button style="padding: 8px 30px;" @click="selectTableHeader = false">取消</el-button>
        <el-button style="padding: 8px 30px;" type="primary" @click="confirm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  query,
  update
} from './api'
import { getToken } from '@/utils/auth'
import permission from '@/directive/permission/index.js' // 权限判断指令
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
import draggable from 'vuedraggable'
export default {
  name: 'Index',
  components: { draggable },
  directives: { permission, elDragDialog },
  props: {
    tag: {
      type: String,
      default: ''
    },
    // 按钮权限
    permission: {
      type: String,
      default: ''
    },
    // 导出文件名称
    fileName: {
      type: String,
      default: ''
    },
    // 查询字段
    exportParam: {
      type: Object,
      default: () => { }
    },
    ids: {
      type: Array,
      default: () => []
    },
    axiosFun: {
      type: Function,
      default: null
    }
  },
  data() {
    return {
      fullscreenLoading: false,
      tableHeaders: [],
      selectTableHeader: false,
      checkedList: [],
      checkAll: false,
      isIndeterminate: false
    }
  },
  methods: {
    onEnd() {
      const a = this.tableHeaders.filter(i => this.checkedList.indexOf(i.prop) >= 0)
      const b = []
      a.forEach(item => {
        b.push(item.prop)
      })
      this.checkedList = Object.assign([], b)
    },
    queryTableHeaders() {
      this.$set(this, 'tableHeaders', [])
      this.$set(this, 'checkedList', [])
      return new Promise((resolve, reject) => {
        query({ pageFlag: this.tag }).then(res => {
          let commonarr = ''
          let personnalarr = ''
          const common = res.data.data.common && res.data.data.common.jsonData || ''
          const personnal = res.data.data.personnal && res.data.data.personnal.jsonData || ''

          commonarr = common ? JSON.parse(common) : []
          personnalarr = personnal ? JSON.parse(personnal) : []
          if (personnalarr && personnalarr.length > 0) {
            this.tableHeaders = Object.assign([], personnalarr)
            personnalarr.forEach(item => {
              if (item.isShow) {
                this.checkedList.push(item.prop)
              }
            })
          } else if (commonarr && commonarr.length > 0) {
            this.tableHeaders = Object.assign([], commonarr)
            commonarr.forEach(item => {
              if (item.isShow) {
                this.checkedList.push(item.prop)
              }
            })
          }
          if (this.checkedList.length === this.tableHeaders.length) { this.checkAll = true }
          this.selectTableHeader = true
        }).catch(error => {
          reject(error)
        })
      })
    },
    handleCheckAllChange(val) {
      this.$set(this, 'checkedList', val ? this.tableHeaders.map(item => item.prop) : [])
      this.isIndeterminate = false
    },
    handleCheckedChange(val) {
      const checkedCount = val.length
      this.checkAll = checkedCount === this.tableHeaders.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.tableHeaders.length
    },
    /**
			 * 确认导出
			 */
    confirm() {
      // 保存用户导出表头记录
      this.saveTableHeaders()
      this.exportFile()
    },
    /**
			 * 保存用户导出表头记录
			 * @returns {Promise<any>}
			 */
    saveTableHeaders() {
      this.tableHeaders.forEach(item => {
        if (this.checkedList.indexOf(item.prop) >= 0) {
          item.isShow = true
        } else {
          item.isShow = false
        }
      })
      const a = Object.assign([], this.tableHeaders)
      const jsonData = JSON.stringify(a)
      return new Promise((resolve, reject) => {
        update({ pageFlag: this.tag, jsonData: jsonData }).then(res => {
        }).catch(error => {
          reject(error)
        })
      })
    },
    /**
			 * 导出文件
			 */
    exportFile() {
      this.fullscreenLoading = true
      let searchObj = {}
      searchObj['token'] = getToken()
      if (this.ids.length > 0) {
        searchObj['ids'] = this.ids.map(item => {
          return item.id
        }).join(',')
      } else {
        const exportParam = Object.assign({}, this.exportParam)
        for (var i in exportParam) {
          if (exportParam[i] instanceof Array) {
            exportParam[i] = exportParam[i].join(',')
          }
        }
        searchObj = Object.assign(searchObj, exportParam)
      }
      searchObj['tableHeaders'] = this.checkedList.join(',')
      return this.axiosFun(searchObj).then(res => {
        console.log(res.data)
        const content = res.data
        const blob = new Blob([content])
        const fileName = this.fileName
        if ('download' in document.createElement('a')) {
          // 非IE下载
          const elink = document.createElement('a')
          elink.download = fileName
          elink.style.display = 'none'
          elink.href = URL.createObjectURL(blob)
          document.body.appendChild(elink)
          elink.click()
          URL.revokeObjectURL(elink.href) // 释放URL 对象
          document.body.removeChild(elink)
        } else {
          // IE10+下载
          navigator.msSaveBlob(blob, fileName)
        }
        this.fullscreenLoading = false
        // eslint-disable-next-line handle-callback-err
      }).catch(err => {
        this.fullscreenLoading = false
      })
    }
  }
}
</script>

<style scoped lang="scss">
</style>
